<template>
  <div class="per">
    <h2>权限</h2>
    <el-tree
      :data="data"
      show-checkbox
      node-key="id"
      ref="tree"
      :default-expanded-keys="user.roles"
      :default-checked-keys="user.roles"
      :props="defaultProps"
      :check-on-click-node="true"
      @getCurrentKey="getCurrentKey"
      >
      <!-- :check-strictly="true" -->
    </el-tree>
    <el-button @click="save">保存</el-button>
    <el-button @click="toAbout">跳转关于</el-button>

  </div>
</template>

<script>
import {resetRouter} from '@/router'
import {mapGetters} from 'vuex'
  export default {
    data() {
      return {
        data: [{
            label: '权限管理',
            id:'1', //有children的id与权限无关
            children: [{
              id: '210',
              label: '权限列表',
            },{
              id: '220',
              label: '添加权限',
            }]
          }, {
            label: '路由嵌套',
            id:'2',
            children: [{
              id: '310',
              label: '菜单一'
            }, {
              id: '320',
              label: '菜单二'
            }, {
              label: '菜单三',
              id:'3',
              children: [{
                id: '331',
                label: '菜单3-1'
              }, {
                id: '332',
                label: '菜单3-2'
              }]
            }]
          }, {
            id: '500',
            label: '关于',
        }],
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      }
    },
    computed:{
      ...mapGetters([
        'user',
      ]),
    },
    // created(){
    //   console.log(this.getCurrentKey())
    // },
    methods:{
      // 获取已选择项id
      getCurrentKey(){
        console.log(this.$refs.tree.getCheckedKeys())
        return this.$refs.tree.getCheckedKeys()
      },
      // 保存选项
      async save(){
        // 重置路由
        resetRouter()
        let roles = this.getCurrentKey()
        // 修改权限，修改导航栏
        this.$store.dispatch('setUserInfo',roles)
        const accessRoutes = await this.$store.dispatch('permission/GenerateRoutes', roles)
        accessRoutes.forEach(item => {
          this.$router.addRoute(item) 
        });
      },
      toAbout(){
        this.$router.push('/about')
      }
    }
  }
</script>

<style lang="scss" scoped>
.per{

}
</style>